import store from "@/store";
import router from "@/router";
import ACCESS_ENUM from "@/access/accessEnum";
import cheakAccess from "@/access/cheakAccess";

router.beforeEach(async (to, from, next) => {
  // 判断当前用户
  if (to.meta?.access === "canAdmin") {
    if (store.state.user.loginUser?.role !== "admin") {
      next("/noAuth");
      return;
    }
  }
  const loginUser = store.state.user.loginUser;
  // 如果之前没有登陆过
  if (!loginUser || !loginUser.userRole) {
    // 等登录成功后在执行后续操作
    await store.dispatch("user/getLoginUser");
  }
  // 要跳转的页面必须要登录
  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    if (!loginUser) {
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    // 如果已经登陆了，但是权限不足，那么跳转到无权限页面
    if (!cheakAccess(loginUser, needAccess)) {
      next("/noAuth");
    }
  }
  next();
});
